const ws = require("ws")

const createWs = (server) => {
    const Ws = ws.Server
    const wss = new Ws({
        server,
        path: "/ws"
    })
    const currUsers = {}
    wss.on("connection", (ws, req) => {
        const id = req.url.split("?")[1].split("=")[1]
        currUsers[id] = ws
        const users = Object.keys(currUsers).map(id => {
            const currUser = global.user.find(item => item.id === id)
            return currUser
        })
        Object.keys(currUsers).forEach(itemid => {
            console.log(itemid);
            currUsers[itemid].send(JSON.stringify({
                type: 0,
                data: users.filter(item => item.id !== itemid)
            }))
        })
        ws.on("message", (data) => {
            const msg = JSON.parse(data)

            console.log(msg, 'msg');

            const curr = global.user.find(item => item.id === msg.data.fromId)
            const to = global.user.find(item => item.id === msg.data.toId)
            const newMsg = {
                type: 1,
                data: {
                    ...msg.data,
                    fromNickname: curr.nickname,
                    toNickname: to.nickname,
                    time: new Date().getTime()
                }
            }
            console.log(newMsg);

            ws.send(JSON.stringify(newMsg))
            currUsers[msg.data.toId] && currUsers[msg.data.toId].send(JSON.stringify(newMsg))
        })
    })
}

module.exports = createWs